package com.example.gulimall.ssoserver.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

@Controller
public class LoginController {

    @Autowired
    private StringRedisTemplate template;

    @PostMapping("/doLogin")
    public String doLogin(@RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("url") String url, HttpServletResponse response){
        if(!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)){
            String uuid = UUID.randomUUID().toString().replace("-","");
            // template.opsForValue().set(uuid,username);
            Cookie sso_token = new Cookie("sso_token",uuid);
            response.addCookie(sso_token);
            return "redirect:"+ url + "?token=" + uuid;
        }
        // 登陆成功后跳回去
        return "login";
    }

    @GetMapping("login")
    public String login(@RequestParam("redirect_url") String url, Model model, @CookieValue(value = "sso_token",required = false) String ssotoken){
        // 在这里很巧妙的取到token然后放在get请求的参数里了
        if(!StringUtils.isEmpty(ssotoken))
            return "redirect:"+url + "?sso_token=" + ssotoken;
        model.addAttribute("url",url);
        return "login";
    }
}
